import { cncryptionCipher, decryptionCipher } from './encode'

// 验证邮箱
export const checkEmail = (email) => {
  const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ //优化邮箱校验
  return pattern.test(email)
}

// 验证密码
export const validPwd = (value) => {
  const pattern = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,20}$/ //密码输入规
  return pattern.test(value)
}

// 二次验证密码
export const surePwd = () => {
  const pwd = document.querySelector('#pwd')
  const pwdSecond = document.querySelector('#pwdSecond')
  return pwd.value == pwdSecond.value
}

// 生成粗略的随机字符串
export const generateRandomString = (length = 10) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length)
    result += chars[randomIndex]
  }
  return result
}

// 验证手机号
export const isValidatePhone = (mobile) => {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(mobile)
}

// 隐藏手机号
export const hidePhone = (mobile) => {
  return mobile.slice(0, 3) + '****' + mobile.slice(7)
}

// 用户token
export const handleLocalUserInfo = () => {
  const key = 'dXNlci1sb2dpbi1pbmZv'
  const getUserToken = () => {
    const token = localStorage.getItem(key)
    if (!token) {
      return {}
    }
    return JSON.parse(decryptionCipher(token))
  }
  const setUserToken = (data) => {
    localStorage.setItem(key, cncryptionCipher(JSON.stringify(data)))
  }
  const clearUserToken = () => {
    localStorage.removeItem(key)
  }
  return {
    getUserToken,
    setUserToken,
    clearUserToken,
  }
}

export const timestampToYmd = (timestamp, needHm) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  if (needHm) {
    const h = date.getHours().toString().padStart(2, '0')
    const m = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${h}:${m}`
  }
  return `${year}-${month}-${day}`
}

// 处理数字规则函数
export const formatNumber = (num, isMoney = false) => {
  if (num == 0) {
    return 0
  }
  if (num < 10000) {
    if (isMoney) {
      const options = { style: 'decimal', maximumFractionDigits: 2 }
      return num.toLocaleString('en-US', options)
    } else {
      return num.toLocaleString()
    }
  } else {
    return (num / 10000).toFixed(1)
  }
}

/**
 * 视口触底判断
 * */
export const isElementInViewport = el => {
  try {
    return el.offsetHeight + el.scrollTop >= el.scrollHeight - 10
  } catch (error) {
    return false
  }
}